/**
 * 视觉相似度对比使用示例
 * 展示如何使用 Puppeteer + pixelmatch + PNG 进行图像对比
 */

import { gradeAssignment, gradeAssignmentSync } from '@/utils/util'

/**
 * 示例1: 使用图像对比的异步评分
 */
export async function gradeWithImageComparison(code: string, assignmentId: number) {
  try {
    // 构建标准答案图片路径
    const referenceImagePath = `/src/assets/reference-images/assignment-${assignmentId}.png`
    
    // 执行异步评分，包含图像对比
    const result = await gradeAssignment(code, assignmentId, referenceImagePath)
    
    console.log('评分结果:', result)
    console.log('总分:', result.score)
    console.log('等级:', result.grade)
    console.log('反馈:', result.feedback)
    
    return result
  } catch (error) {
    console.error('图像对比评分失败:', error)
    
    // 回退到同步评分
    return gradeAssignmentSync(code, assignmentId)
  }
}

/**
 * 示例2: 批量评分多个学生作业
 */
export async function batchGradeWithImageComparison(
  submissions: Array<{ code: string; studentId: string }>,
  assignmentId: number
) {
  const results = []
  const referenceImagePath = `/src/assets/reference-images/assignment-${assignmentId}.png`
  
  for (const submission of submissions) {
    try {
      const result = await gradeAssignment(
        submission.code, 
        assignmentId, 
        referenceImagePath
      )
      
      results.push({
        studentId: submission.studentId,
        ...result
      })
    } catch (error) {
      console.error(`学生 ${submission.studentId} 评分失败:`, error)
      
      // 回退到同步评分
      const fallbackResult = gradeAssignmentSync(submission.code, assignmentId)
      results.push({
        studentId: submission.studentId,
        ...fallbackResult,
        note: '使用代码分析评分（图像对比失败）'
      })
    }
  }
  
  return results
}

/**
 * 示例3: 在Vue组件中使用
 */
export const useVisualGrading = () => {
  const gradeCode = async (code: string, assignmentId: number) => {
    // 检查是否有标准答案图片
    const referenceImagePath = `/src/assets/reference-images/assignment-${assignmentId}.png`
    
    try {
      // 尝试使用图像对比评分
      const result = await gradeAssignment(code, assignmentId, referenceImagePath)
      
      return {
        ...result,
        method: 'visual-comparison'
      }
    } catch (error) {
      console.warn('图像对比不可用，使用代码分析:', error)
      
      // 回退到代码分析
      const result = gradeAssignmentSync(code, assignmentId)
      
      return {
        ...result,
        method: 'code-analysis'
      }
    }
  }
  
  return {
    gradeCode
  }
}

/**
 * 示例4: 待办事项作业的专门评分
 */
export async function gradeTodoAssignment(code: string) {
  const assignmentId = 7 // 待办事项作业ID
  
  try {
    // 使用专门的待办事项标准答案图片
    const result = await gradeAssignment(
      code, 
      assignmentId, 
      '/src/assets/reference-images/sample-todo.svg'
    )
    
    // 添加待办事项特定的反馈
    const todoSpecificFeedback = analyzeTodoFeatures(code)
    
    return {
      ...result,
      todoFeatures: todoSpecificFeedback
    }
  } catch (error) {
    console.error('待办事项评分失败:', error)
    return gradeAssignmentSync(code, assignmentId)
  }
}

/**
 * 示例5: 针对待办事项列表的特定评分测试
 */
export async function testTodoListGrading() {
  const todoListCode = `
<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: Arial, sans-serif; background: #f5f5f5; margin: 0; padding: 20px; }
    .todo-container { max-width: 1100px; margin: 0 auto; background: white; border-radius: 8px; overflow: hidden; }
    .header { background: #4a90e2; color: white; padding: 25px; text-align: center; }
    .header h1 { margin: 0; font-size: 32px; }
    .input-section { padding: 20px; display: flex; gap: 20px; }
    .todo-input { flex: 1; padding: 15px; border: 2px solid #ddd; border-radius: 4px; font-size: 16px; }
    .add-btn { padding: 15px 30px; background: #28a745; color: white; border: none; border-radius: 4px; font-size: 16px; cursor: pointer; }
    .todo-item { display: flex; align-items: center; padding: 20px; border-bottom: 1px solid #eee; }
    .todo-item input[type="checkbox"] { margin-right: 20px; width: 16px; height: 16px; }
    .todo-item span { flex: 1; font-size: 16px; }
    .todo-item.completed span { text-decoration: line-through; color: #666; }
    .delete-btn { padding: 10px 20px; background: #dc3545; color: white; border: none; border-radius: 4px; font-size: 14px; cursor: pointer; }
    .stats { padding: 20px; background: #f8f9fa; border-top: 1px solid #dee2e6; color: #6c757d; font-size: 14px; }
  </style>
</head>
<body>
  <div class="todo-container">
    <div class="header">
      <h1>Todo List Application</h1>
    </div>
    <div class="input-section">
      <input type="text" class="todo-input" placeholder="Add new task...">
      <button class="add-btn">Add Task</button>
    </div>
    <div id="todo-list">
      <div class="todo-item">
        <input type="checkbox">
        <span>Complete project documentation</span>
        <button class="delete-btn">Delete</button>
      </div>
      <div class="todo-item completed">
        <input type="checkbox" checked>
        <span>Review code changes</span>
        <button class="delete-btn">Delete</button>
      </div>
      <div class="todo-item">
        <input type="checkbox">
        <span>Update user interface</span>
        <button class="delete-btn">Delete</button>
      </div>
    </div>
    <div class="stats">
      Total: 3 tasks | Completed: 1 | Remaining: 2
    </div>
  </div>
</body>
</html>
`

  try {
    const todoResult = await gradeAssignment(todoListCode, 1, '/src/assets/reference-images/sample-todo.svg')
    console.log('Todo List Grading Result:', todoResult)
    return todoResult
  } catch (error) {
    console.error('Todo list grading failed:', error)
    // 回退到同步评分
    const fallbackResult = gradeAssignmentSync(todoListCode, 1)
    console.log('Fallback Grading Result:', fallbackResult)
    return fallbackResult
  }
}

/**
 * 分析待办事项特定功能
 */
function analyzeTodoFeatures(code: string) {
  const features = {
    hasAddInput: /input[^>]*type\s*=\s*["']text["']/gi.test(code),
    hasAddButton: /button[^>]*|input[^>]*type\s*=\s*["']button["']/gi.test(code),
    hasTaskList: /ul\s*{|li\s*{|list-style/gi.test(code),
    hasDeleteFunction: /delete|remove|删除/gi.test(code),
    hasCompleteFunction: /complete|done|完成|已完成/gi.test(code),
    hasResponsiveDesign: /@media|max-width|min-width/gi.test(code)
  }
  
  const implementedFeatures = Object.values(features).filter(Boolean).length
  const totalFeatures = Object.keys(features).length
  
  return {
    features,
    completionRate: `${implementedFeatures}/${totalFeatures}`,
    percentage: Math.round((implementedFeatures / totalFeatures) * 100)
  }
}